<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="disabled"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="选择销售单" prop="relaSaleNo">
            <el-select
              :disabled="formType !== 'create'"
              v-model="formData.relaSaleNo"
              clearable
              filterable
              placeholder="请选择销售单"
              class="!w-1/1"
              @change="handleSaleOrderChange"
            >
              <el-option
                v-for="item in saleOrderList"
                :key="item.id"
                :label="item.no"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="退货单号" prop="no" v-else>
            <el-input v-model="formData.no" placeholder="请输入订单编号" disabled />
          </el-form-item> -->
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="关联销售单" prop="relaSaleNo">
            <el-input v-model="formData.relaSaleNo" placeholder="关联销售单号" disabled />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="订单备注" prop="remark">
            <el-input
              type="textarea"
              v-model="formData.remark"
              :rows="1"
              placeholder="请输入备注"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 子表的表单 -->
      <ContentWrap>
        <el-tabs v-model="subTabsName" class="-mt-15px -mb-10px">
          <el-tab-pane label="订单产品清单" name="item">
            <SaleOrderItemForm
              ref="itemFormRef"
              :items="formData.items || []"
              :disabled="disabled"
            />
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-if="!disabled">
        确 定
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { SaleOrderApi, SaleOrderVO } from '@/api/erp/sale/order'
import SaleOrderItemForm from './components/SaleOrderItemForm.vue'
// import SaleOrderReturnEnableList from './components/SaleOrderReturnEnableList.vue'
import { SaleReturnApi, SaleReturnVO } from '@/api/erp/salereturn'
import { erpPriceMultiply } from '@/utils'
// import { createApp } from 'vue'

/** ERP 销售退货表单 */
defineOptions({ name: 'SaleReturnForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；detail - 详情
const formData = ref({
  id: undefined as number | undefined,
  no: undefined as string | undefined, // 退货单号，后端返回
  relaSaleNo: undefined as string | undefined, // 关联的销售单编号
  saleOrderId: undefined as number | undefined, // 销售订单ID
  status: undefined as number | undefined, // 订单状态
  orderTime: new Date(), // 下单时间，默认当前时间
  returnCount: 0, // 销售退货总数量
  returnPrice: 0, // 销售退货总金额
  totalCount: 0, // 退货后合计数量
  totalProductPrice: 0, // 退货后合计产品价格
  discountPercent: 0, // 折扣百分比
  discountPrice: 0, // 折扣金额
  totalPrice: 0, // 总价格
  discountPayPrice: 0, // 折扣后支付价格
  remark: undefined as string | undefined, // 备注
  items: [] as any[] // 退货产品项
})

const formRules = reactive({
  remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
  saleOrderId: [{ required: true, message: '销售单不能为空', trigger: 'blur' }]
})

const disabled = computed(() => formType.value === 'detail')
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('item')
const itemFormRef = ref()

// 销售单选择相关
const saleOrderNo = ref('') // 销售单号
const saleOrderList = ref<SaleOrderVO[]>([]) // 销售单列表
// const saleOrderSelectRef = ref() // 销售单选择组件引用

/** 打开销售单选择 */
// const openSaleOrderSelect = () => {
//   // 创建销售单选择组件的实例
//   if (!saleOrderSelectRef.value) {
//     saleOrderSelectRef.value = createApp(SaleOrderReturnEnableList).mount(
//       document.createElement('div')
//     )
//     // 监听选择成功事件
//     saleOrderSelectRef.value.$on('success', (row: SaleOrderVO) => {
//       // 设置销售单信息
//       formData.value.saleOrderId = row.id
//       saleOrderNo.value = row.no
//       formData.value.relaSaleNo = row.no
//       // 设置产品项
//       formData.value.items = row.items?.map((item) => ({
//         ...item,
//         count: 1, // 默认数量为1
//         taxPercent: 0 // 默认税率为0
//       }))
//     })
//   }
// 打开销售单选择弹窗
//   saleOrderSelectRef.value.open()
// }

/** 计算 discountPrice、totalPrice 价格 */
watch(
  () => formData.value,
  (val) => {
    console.log('val', val)
    if (!val) {
      return
    }
    const totalPrice = (val.items || []).reduce<number>(
      (prev, curr) =>
        prev +
        (curr && typeof curr === 'object' && 'totalPrice' in curr
          ? Number((curr as any).totalPrice || 0)
          : 0),
      0
    )
    const discountPrice =
      val.discountPercent != null ? erpPriceMultiply(totalPrice, val.discountPercent / 100.0) : 0
    formData.value.discountPrice = discountPrice || 0 // 使用空值合并确保赋值为数字类型
    formData.value.totalPrice = totalPrice - (discountPrice || 0)
    formData.value.totalProductPrice = totalPrice
    formData.value.discountPayPrice = totalPrice - (discountPrice || 0)
    // val.totalTaxPrice!= null? erpPriceMultiply(totalPrice, val.totalTaxPrice / 100.0) : 0
    // 需要先在formData的类型定义中添加totalProductPrice属性
    // (formData.value as any).totalProductPrice = totalPrice
    //     formData.value.totalTaxPrice =
    //       val.totalTaxPrice!= null? erpPriceMultiply(totalPrice, val.totalTaxPrice / 100.0) : 0
    //     formData.value.discountPayPrice =
    //       val.discountPayPrice != null ? erpPriceMultiply(totalPrice, val.discountPayPrice / 100.0) : 0
    //     // 计算收取订金
    //       val.depositPrice != null ? erpPriceMultiply(totalPrice, val.depositPrice / 100.0) : 0
  },
  { deep: true }
)

/** 处理销售单变更 */
const handleSaleOrderChange = async (saleOrderId: number) => {
  if (!saleOrderId) return
  formLoading.value = true
  try {
    // 获取销售单详情
    const saleOrder = await SaleOrderApi.getSaleOrder(saleOrderId)
    // 设置销售单信息
    formData.value.saleOrderId = saleOrder.id
    saleOrderNo.value = saleOrder.no
    formData.value.relaSaleNo = saleOrder.no
    // 设置产品项
    formData.value.items = saleOrder.items?.map((item) => ({
      ...item
    }))
  } catch (error) {
    console.error('获取销售单详情失败:', error)
    message.error('获取销售单详情失败')
  } finally {
    formLoading.value = false
  }
}

/** 加载可退货的销售单列表 */
const loadSaleOrderList = async () => {
  formLoading.value = true
  try {
    const data = await SaleOrderApi.getSaleOrdersimpleList()
    saleOrderList.value = data || []
  } catch (error) {
    message.error('加载销售单列表失败')
  } finally {
    formLoading.value = false
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 如果是创建模式，加载销售单列表
  if (type === 'create') {
    await loadSaleOrderList()
  }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await SaleReturnApi.getSaleReturn(id)
      console.log('编辑模式加载的数据:', formData.value)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  await itemFormRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as SaleReturnVO
    if (formType.value === 'create') {
      await SaleReturnApi.createSaleReturn(data)
      message.success(t('common.createSuccess'))
    } else {
      await SaleReturnApi.updateSaleReturn(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined as number | undefined,
    no: undefined as string | undefined, // 退货单号，后端返回
    relaSaleNo: undefined as string | undefined, // 关联的销售单编号
    saleOrderId: undefined as number | undefined, // 销售订单ID
    status: undefined as number | undefined, // 订单状态
    orderTime: new Date(), // 下单时间，默认当前时间
    returnCount: 0, // 销售退货总数量
    returnPrice: 0, // 销售退货总金额
    totalCount: 0, // 退货后合计数量
    totalProductPrice: 0, // 退货后合计产品价格
    discountPercent: 0, // 折扣百分比
    discountPrice: 0, // 折扣金额
    totalPrice: 0, // 总价格
    discountPayPrice: 0, // 折扣后支付价格
    remark: undefined as string | undefined, // 备注
    items: [] as any[] // 退货产品项
  }
  saleOrderNo.value = ''
  formRef.value?.resetFields()
}
</script>
